<?php

namespace src;

use RuntimeException;

class Facade
{
    /**
     * @var Application
     */
    protected static $app;

    /**
     * 解析过的实例对象
     * @var array
     */
    protected static $resolvedInstance;

    public static function setFacadeApplication($app)
    {
        static::$app = $app;
    }

    /**
     * 实现类设置组件注册别名
     * @return mixed
     */
    protected static function getFacadeAccessor()
    {
        throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
    }

    //获取实例对象
    public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }

    //获取实例对象方法
    protected static function resolveFacadeInstance($name)
    {
        //如果是对象直接返回
        if (is_object($name)) {
            return $name;
        }
        //解析过直接返回
        if (isset(static::$resolvedInstance[$name])){
            return  static::$resolvedInstance[$name];
        }
        //如果得到容器对象，则从容器中解析
        if (static::$app){
            return static::$resolvedInstance[$name] = static::$app[$name];
        }
    }

    public static function __callStatic($method, $args)
    {
        //从容器中获取服务
        $instance = static::getFacadeRoot();
        if (!$instance){
            throw new RuntimeException('没有找到门面的服务.');
        }
        return $instance->$method(...$args);
    }

}